package com.win.logback;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import org.apache.commons.lang3.time.FastDateFormat;


public class LogbackFitler extends Filter<ILoggingEvent> {

    private static final FastDateFormat FAST_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS");

    @Override
    public FilterReply decide(ILoggingEvent event) {

        StringBuilder exception = new StringBuilder();
        IThrowableProxy iThrowableProxy1 = event.getThrowableProxy();
        if (iThrowableProxy1 != null) {
            exception.append(iThrowableProxy1.getClassName()).append(" ").append(iThrowableProxy1.getMessage()).append("\r\n");
            for (int i = 0; i < iThrowableProxy1.getStackTraceElementProxyArray().length; i++) {
                exception.append(iThrowableProxy1.getStackTraceElementProxyArray()[i].toString()).append("\r\n");
            }
        }
        if (exception.length() > 0) {
            exception.insert(0, "\r\n");
            exception.append("\r\n");
        }
        LoggerMessage loggerMessage = new LoggerMessage(
                event.getFormattedMessage(),
                FAST_DATE_FORMAT.format(event.getTimeStamp()),
                event.getThreadName(),
                event.getLoggerName(),
                event.getLevel().levelStr,
                exception.toString(),
                ""
        );
        LoggerPusher.QUEUE.add(loggerMessage);
        return FilterReply.ACCEPT;
    }
}
